/**
 * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.jmyd.sharding.util;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;

import java.security.SecureRandom;
import java.util.UUID;

/**
 * 封装各种生成唯一性ID算法的工具类.
 *
 * @author ThinkGem
 * @version 2013-01-15
 */
public final class IdGen {
    private IdGen(){}

    private static SecureRandom random = new SecureRandom();

    /**
     * 封装JDK自带的UUID, 通过Random数字生成, 中间无-分割.
     */
    public static String uuid() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    /**
     * Guid生成方法
     */
    public static String generateGuid() {
        return RandomStringUtils.random(32, true, true).toLowerCase();
    }

    /**
     * 使用SecureRandom随机生成Long.
     */
    public static long randomLong() {
        return Math.abs(random.nextLong());
    }

    /**
     * 基于Base64编码的SecureRandom随机生成bytes.
     */
    public static String randomBase64(int length) {
        byte[] randomBytes = new byte[length];
        random.nextBytes(randomBytes);
        return new String(randomBytes);
    }

    public static UUID fromString(String val) {
        if (StringUtils.isEmpty(val) || val.length() < 32) {
            return null;
        }
        //如果是带-的，则直接转
        if (val.contains("-")) {
            try {
                return UUID.fromString(val);
            } catch (Exception e) {
                return null;
            }

        }
        String one = val.substring(0, 8);
        String two = val.substring(8, 12);
        String tree = val.substring(12, 16);
        String four = val.substring(16, 20);
        String five = val.substring(20);
        String uuid = one + "-" + two + "-" + tree + "-" + four + "-" + five;
        try {
            return UUID.fromString(uuid);
        } catch (Exception e) {
            return null;
        }
    }

    public static void main(String[] args) {
        System.out.println(IdGen.fromString(IdGen.fromString("608859871b61424794c7dff348347f93").toString()));

        System.out.println(uuid());
        System.out.println(generateGuid());
        System.out.println(randomLong());
    }

}
